package com.tyut.musicdreamer.service.user.service.impl;

import com.tyut.musicdreamer.service.user.api.UserService;
import com.tyut.musicdreamer.service.user.api.model.UserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * 用户服务API实现类
 * 实现API模块中定义的接口，供其他服务调用
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceApiImpl implements UserService {

    private final com.tyut.musicdreamer.service.user.service.UserService userServiceImpl;

    @Override
    public UserVO getUserInfo(Long userId) {
        com.tyut.musicdreamer.service.user.model.vo.UserVO originalVO = userServiceImpl.getUserInfo(userId);
        return convertToApiUserVO(originalVO);
    }

    @Override
    public String getUserName(Long userId) {
        try {
            com.tyut.musicdreamer.service.user.model.vo.UserVO userVO = userServiceImpl.getUserInfo(userId);
            return userVO != null ? userVO.getUsername() : "用户" + userId;
        } catch (Exception e) {
            log.error("获取用户名失败，用户ID: {}", userId, e);
            return "用户" + userId;
        }
    }

    @Override
    public String getUserAvatar(Long userId) {
        try {
            com.tyut.musicdreamer.service.user.model.vo.UserVO userVO = userServiceImpl.getUserInfo(userId);
            return userVO != null ? userVO.getAvatar() : null;
        } catch (Exception e) {
            log.error("获取用户头像失败，用户ID: {}", userId, e);
            return null;
        }
    }

    @Override
    public UserVO updateUserInfo(Long userId, String username, String email) {
        com.tyut.musicdreamer.service.user.model.vo.UserVO originalVO = userServiceImpl.updateUserInfo(userId, username, email);
        return convertToApiUserVO(originalVO);
    }

    @Override
    public String updateAvatar(Long userId, String avatarUrl) {
        throw new UnsupportedOperationException("此方法不支持直接调用，请使用原始服务的方法");
    }

    @Override
    public boolean updatePassword(Long userId, String oldPassword, String newPassword) {
        return userServiceImpl.updatePassword(userId, oldPassword, newPassword);
    }

    @Override
    public boolean checkUserExists(Long userId) {
        try {
            userServiceImpl.getUserInfo(userId);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 将原始UserVO转换为API模块的UserVO
     */
    private UserVO convertToApiUserVO(com.tyut.musicdreamer.service.user.model.vo.UserVO originalVO) {
        if (originalVO == null) {
            return null;
        }
        
        UserVO apiVO = new UserVO();
        BeanUtils.copyProperties(originalVO, apiVO);
        return apiVO;
    }
} 